from uuid import UUID

from injector import inject
from dataclasses import dataclass
from internal.model import DataSet
from internal.schema import DatasetSchema, DatasetWithPageReq
from internal.schema.dataset_schema import DatasetResponseSchema, DatasetResponseSchemaList
from pkg.resp import validate_error_json, success_message, success_json
from internal.service import DatasetService
from pkg.pageinator import PageModel


@inject
@dataclass
class DatasetHandler:
    dataset_service: DatasetService

    def create_dateset(self):
        req = DatasetSchema()
        if not req.validate():
            return validate_error_json(req.errors)
        self.dataset_service.created_dataset(req)
        return success_message("创建成功")

    def get_dataset(self, dataset_id: UUID) -> DataSet:
        data = self.dataset_service.get_dataset(dataset_id)
        resp = DatasetResponseSchema()
        return success_json(resp.dump(data))

    def update_dataset(self, dataset_id: UUID) -> DataSet:
        req = DatasetSchema()
        if not req.validate():
            return validate_error_json(req.errors)
        self.dataset_service.update_dataset(dataset_id, req)
        return success_message("更新成功")

    def get_dataset_with_page(self):
        req = DatasetWithPageReq()
        if not req.validate():
            return validate_error_json(req.errors)
        data_list, pageinator = self.dataset_service.dataset_with_page(req)
        resp = DatasetResponseSchemaList(many=True)
        return success_json(PageModel(list=resp.dump(data_list), paginator=pageinator))
